import React, { useState, useEffect } from 'react';
import { Card, CardContent, Typography, Divider, List, ListItem, ListItemText, ListItemIcon, IconButton, Box, Chip } from '@mui/material';
import { Warning, Info, LocationOn, ChevronRight, CheckCircle, Refresh } from '@mui/icons-material';
import { red, amber, green } from '@mui/material/colors';
import { apiRequest } from '../utils/api';

// 获取紧急警报数据
const fetchEmergencyAlerts = async (vehicleId) => {
  try {
    // 调用后端API获取警报数据
    const data = await apiRequest.get(`/api/alerts/vehicle/${vehicleId}`);
    // 转换数据格式以适配组件显示
    return data.map(alert => ({
      id: alert.id,
      type: alert.alertType,
      timestamp: alert.createdAt,
      location: { lat: alert.latitude, lng: alert.longitude },
      status: alert.status,
      description: alert.description
    }));
  } catch (error) {
    console.error('Failed to fetch emergency alerts:', error);
    // 在开发环境中尝试从localStorage获取模拟数据
    if (process.env.NODE_ENV === 'development') {
      try {
        const storedAlerts = localStorage.getItem('alerts');
        if (storedAlerts) {
          const alerts = JSON.parse(storedAlerts);
          // 如果指定了vehicleId，则只返回该车辆的警报
          if (vehicleId) {
            return alerts.filter(alert => alert.vehicleId === vehicleId);
          }
          return alerts;
        }
      } catch (storageError) {
        console.error('Failed to get alerts from localStorage:', storageError);
      }
    }
    
    // 返回默认模拟数据用于开发和调试
    return [
      {
        id: '1',
        vehicleId: vehicleId || 'vehicle-001',
        type: 'THEFT_ATTEMPT',
        timestamp: new Date(Date.now() - 300000).toISOString(),
        location: { lat: 39.9042, lng: 116.4074 },
        status: 'ACTIVE',
        description: 'Unauthorized access detected'
      },
      {
        id: '2',
        vehicleId: vehicleId || 'vehicle-001',
        type: 'ENGINE_OVERHEAT',
        timestamp: new Date(Date.now() - 600000).toISOString(),
        location: { lat: 39.9142, lng: 116.4174 },
        status: 'RESOLVED',
        description: 'Engine temperature exceeded threshold'
      },
      {
        id: '3',
        vehicleId: vehicleId || 'vehicle-001',
        type: 'BATTERY_LOW',
        timestamp: new Date(Date.now() - 900000).toISOString(),
        location: { lat: 39.9242, lng: 116.4274 },
        status: 'WARNING',
        description: 'Battery level below 20%'
      },
      {
        id: '4',
        vehicleId: vehicleId || 'vehicle-002',
        type: 'TIRE_PRESSURE_LOW',
        timestamp: new Date(Date.now() - 1200000).toISOString(),
        location: { lat: 39.9342, lng: 116.4374 },
        status: 'WARNING',
        description: 'Left front tire pressure below recommended level'
      },
      {
        id: '5',
        vehicleId: vehicleId || 'vehicle-003',
        type: 'DOOR_OPEN',
        timestamp: new Date(Date.now() - 1500000).toISOString(),
        location: { lat: 39.9442, lng: 116.4474 },
        status: 'ACTIVE',
        description: 'Door remains open for extended period'
      }
    ];
  }
};
const EmergencyAlert = ({ vehicleId }) => {
  const [alerts, setAlerts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [activeAlert, setActiveAlert] = useState(null);

  useEffect(() => {
    const loadAlerts = async () => {
      try {
        setLoading(true);
        const data = await fetchEmergencyAlerts(vehicleId);
        setAlerts(data);
        // 设置最新的活动警报
        const latestActive = data.find(alert => alert.status === 'ACTIVE');
        if (latestActive) {
          setActiveAlert(latestActive);
        }
        setError(null);
      } catch (err) {
        setError('Failed to load emergency alerts.');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    loadAlerts();
    // 每15秒刷新一次数据
    const interval = setInterval(loadAlerts, 15000);
    return () => clearInterval(interval);
  }, [vehicleId]);

  const resolveAlert = async (alertId) => {
    try {
      // 调用后端API解决警报
      await apiRequest.put(`/api/alerts/${alertId}/resolve`, { resolvedBy: 'System User' });
      // 更新本地状态
      setAlerts(alerts.map(alert => 
        alert.id === alertId ? { ...alert, status: 'RESOLVED' } : alert
      ));
      // 如果解决的是活动警报，清除活动警报
      if (activeAlert && activeAlert.id === alertId) {
        setActiveAlert(null);
      }
    } catch (error) {
      console.error('Failed to resolve alert:', error);
      // 显示错误消息给用户
      setError('Failed to resolve alert. Please try again.');
      // 3秒后清除错误消息
      setTimeout(() => setError(null), 3000);
    }
  };

  const getAlertSeverity = (status) => {
    switch (status) {
      case 'ACTIVE':
        return 'error';
      case 'WARNING':
        return 'warning';
      case 'RESOLVED':
        return 'success';
      default:
        return 'info';
    }
  };

  const getAlertColor = (status) => {
    switch (status) {
      case 'ACTIVE':
        return red[500];
      case 'WARNING':
        return amber[500];
      case 'RESOLVED':
        return green[500];
      default:
        return '#2196f3';
    }
  };

  const getAlertIcon = (status) => {
    switch (status) {
      case 'ACTIVE':
        return <Warning style={{ color: red[500] }} />;
      case 'WARNING':
          return <Warning style={{ color: amber[500] }} />;
      case 'RESOLVED':
        return <CheckCircle style={{ color: green[500] }} />;
      default:
        return <Warning />;
    }
  };

  if (loading) {
    return (
      <Card>
        <CardContent>
          <Typography variant="h6" align="center">Loading emergency alerts...</Typography>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card>
        <CardContent>
          <Typography variant="h6" color="error" align="center">{error}</Typography>
        </CardContent>
      </Card>
    );
  }

  return (
    <div>
      {/* 活动警报通知 */}
      {activeAlert && (
        <Card sx={{ mb: 4, borderLeft: `4px solid ${red[500]}` }}>
          <CardContent sx={{ display: 'flex', alignItems: 'center', bgcolor: red[50] }}>
            <Warning sx={{ color: red[500], mr: 2, fontSize: 32 }} />
            <div sx={{ flexGrow: 1 }}>
              <Typography variant="h6" color="error">
                Emergency Alert: {activeAlert.type.replace('_', ' ')}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                {activeAlert.description} - {new Date(activeAlert.timestamp).toLocaleString()}
              </Typography>
            </div>
            <IconButton onClick={() => resolveAlert(activeAlert.id)} color="inherit">
              <CheckCircle sx={{ color: green[500] }} />
            </IconButton>
          </CardContent>
        </Card>
      )}

      {/* 警报列表 */}
      <Card>
        <CardContent>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
            <Typography variant="h5" gutterBottom>Emergency Alerts</Typography>
            <IconButton onClick={() => fetchEmergencyAlerts(vehicleId)} color="inherit">
              <Refresh size={20} />
            </IconButton>
          </Box>
          <Typography variant="subtitle1" color="text.secondary" gutterBottom>
            Vehicle ID: {vehicleId}
          </Typography>
          <Divider sx={{ mb: 3 }} />

          {alerts.length === 0 ? (
            <Typography variant="body1" align="center" color="text.secondary">
              No emergency alerts found
            </Typography>
          ) : (
            <List sx={{ maxHeight: 400, overflow: 'auto' }}>
              {alerts.map((alert) => (
                <ListItem key={alert.id} divider>
                  <ListItemIcon>
                    {getAlertIcon(alert.status)}
                  </ListItemIcon>
                  <ListItemText
                    primary={
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <span>{alert.type.replace('_', ' ')}</span>
                        <Chip
                          label={alert.status}
                          size="small"
                          style={{ backgroundColor: getAlertColor(alert.status), color: 'white' }}
                        />
                      </Box>
                    }
                    secondary={
                      <div>
                        <Typography component="span" color="text.secondary" sx={{ display: 'block' }}>
                          {alert.description}
                        </Typography>
                        <Box sx={{ display: 'flex', alignItems: 'center', mt: 1 }}>
                          <Info size={16} sx={{ mr: 1, color: 'text.secondary' }} />
                          <Typography component="span" variant="caption" color="text.secondary">
                            {new Date(alert.timestamp).toLocaleString()}
                          </Typography>
                          <LocationOn size={16} sx={{ ml: 3, mr: 1, color: 'text.secondary' }} />
                          <Typography component="span" variant="caption" color="text.secondary">
                            {alert.location.lat.toFixed(4)}, {alert.location.lng.toFixed(4)}
                          </Typography>
                        </Box>
                      </div>
                    }
                  />
                  {alert.status !== 'RESOLVED' && (
                    <IconButton onClick={() => resolveAlert(alert.id)} edge="end" aria-label="resolve">
                      <CheckCircle size={20} style={{ color: green[500] }} />
                    </IconButton>
                  )}
                  <ChevronRight size={20} color="text.secondary" />
                </ListItem>
              ))}
            </List>
          )}
        </CardContent>
      </Card>
    </div>
  );
};

export default EmergencyAlert;